package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.AdminDao;
import com.leoman.entity.Admin;
import com.leoman.service.AdminService;
import com.leoman.utils.Md5Util;
import com.leoman.utils.RandomUtil;
import com.leoman.utils.SendMsgUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * AdminServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:56.
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao adminDao;

    @Override
    public List<Admin> findAll() {
        return adminDao.findAll();
    }

    @Override
    public Page<Admin> find(int pageNum, int pageSize) {
        return adminDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Admin> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Admin getById(int id) {
        return adminDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        adminDao.delete(id);
    }

    @Override
    public Admin create(Admin admin) {
        return adminDao.save(admin);
    }

    @Override
    public Admin update(Admin admin) {
        return adminDao.save(admin);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Admin loginIn(HttpServletRequest request, String account, String password) {
        Admin admin = adminDao.findOneByAccount(account);

        if (null != admin && admin.getPassword().equals(password)) {
            request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, admin);
            return admin;
        }

        return null;
    }

    @Override
    public void loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
    }

    @Override
    public Page<Admin> pageByParams(final String account, final String mobile, Integer pageNum, Integer pageSize) {
        return adminDao.findAll(new Specification<Admin>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotBlank(account)) {
                    Predicate pre = cb.like(root.get("account").as(String.class), "%" + account + "%");
                    predicateList.add(pre);
                }
                if (StringUtils.isNotBlank(mobile)) {
                    Predicate pre = cb.like(root.get("mobile").as(String.class), "%" + mobile + "%");
                    predicateList.add(pre);
                }
                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Integer saveAdminUser(Integer adminUserId, String account, String mobile, String password, String nickName, String remark, String wxNum) {
        try {
            Admin admin;
            Admin accountAdmin = adminDao.findOneByAccount(account);
            Admin mobileAdmin = adminDao.findOneByMobile(mobile);

            if (null == adminUserId) {
                admin = new Admin();
                admin.setCreateTime(System.currentTimeMillis());
            } else {
                admin = adminDao.findOne(adminUserId);
            }

            if (null != accountAdmin) {
                if (null == admin.getId() || !admin.getId().equals(accountAdmin.getId())) {
                    return -1;
                }
            }

            if (null != mobileAdmin) {
                if (null == admin.getId() || !admin.getId().equals(mobileAdmin.getId())) {
                    return -2;
                }
            }

            admin.setAccount(account);
            admin.setMobile(mobile);
            admin.setPassword(password.length() > 20 ? password : Md5Util.md5(password));
            admin.setNickname(nickName);
            admin.setRemark(remark);
            admin.setWxNum(wxNum);

            adminDao.save(admin);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer deleteAdminUser(HttpServletRequest request, Integer adminUserId) {
        Integer flag = 1;

        try {
            Admin sessionAdmin = (Admin) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            adminDao.delete(adminUserId);

            if (sessionAdmin.getId().equals(adminUserId)) {
                request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
                flag = 100;
            }

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer reSetAdminUserPassword(HttpServletRequest request, Integer adminUserId) {
        Integer flag = 1;

        try {
            Admin sessionAdminUser = (Admin) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            Admin adminUser = adminDao.findOne(adminUserId);

            if (StringUtils.isBlank(adminUser.getMobile())) {
                return -1;
            }

            if (sessionAdminUser.getId().equals(adminUserId)) {
                request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
                flag = 100;
            }

            String newPassword = RandomUtil.getCode();
            adminUser.setPassword(Md5Util.md5(newPassword));
            System.out.println("管理员 " + adminUser.getAccount() + " 重置后的新密码为：" + newPassword);

            // 发送验证码
            SendMsgUtil.sendMsg(adminUser.getMobile(), newPassword, 1);

            adminDao.save(adminUser);

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchDeleteAdminUser(HttpServletRequest request, Integer[] adminUserIds) {
        Integer flag = 1;

        try {
            Admin sessionAdminUser = (Admin) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            for (Integer adminUserId : adminUserIds) {
                if (null == adminUserId) {
                    continue;
                }
                if (sessionAdminUser.getId().equals(adminUserId)) {
                    request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
                    flag = 100;
                }

                adminDao.delete(adminUserId);
            }

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}